 <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class apis extends CI_Controller {
	var $data;
	public function __construct()
	{
		parent::__construct();		
		$this->load->library('session');
		$this->load->library('pagination');
		$data['title'] = "APIS";		
		$this->load->model('model_companies');
		$this->load->model('model_customer');
		$this->load->model('model_feeds');
		$this->load->model('model_user');
		$this->load->model('model_conflict');
		
		// CHECK LOGIN
		$check = $this->session->userdata('login');
		//if($check==false){
		//	redirect(base_url().'login/', 'refresh');
		//	return;
		//}
	}
	
	public function index()
	{
		
	}

	function upload_comp(){
    	if(isset($_REQUEST['id'])){
    			$data = array('comp_id' => $_REQUEST['id']);
				$result = $this->model_companies->selectIDDetail($data);
				if(count($result) >0){	
					$picture = json_decode($result['comp_img_verify'],true);

					if(isset($_FILES['Filedata']['tmp_name']) && $_FILES['Filedata']['tmp_name'] != ""){
						$content = base64_encode(file_get_contents($_FILES['Filedata']['tmp_name']));

						$url = 'http://localhost/alta_upload/api.php';
						$post = 'key='.urlencode('ALTA@UPLOAD@2013').'&upload='.urlencode($content).'&format=json';
						$ch = curl_init();
						curl_setopt($ch, CURLOPT_POST ,1);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
						curl_setopt($ch, CURLOPT_URL, $url);
						curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3");
						curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
						$result = curl_exec($ch);
						curl_close($ch);

						$img_array = json_decode($result,true);
					

						if($img_array['status_code'] == 200){
							$img_str =  str_replace("localhost/alta_upload","img.altamedia.vn",$img_array['data']['image_url']);

							$picture[] =$img_str;

							$dataArray['comp_img_verify'] = json_encode($picture);

							$this->model_companies->update($dataArray,$_REQUEST['id']);

							echo json_encode(array('result' => 1,'link' => $img_str,'msg' => 'Upload thành công'));
						}
						else echo json_encode(array('result' => 0,'msg' => 'Upload không thành công'));
					}
					else echo json_encode(array('result' => 0,'msg' => 'Upload không thành công'));
				}
			else echo json_encode(array('result' => 0,'msg' => 'Upload không thành công'));
    	}
    	else echo json_encode(array('result' => 0,'msg' => 'Thiếu thông tin'));
	}

	function upload_tax(){
    	if(isset($_REQUEST['id'])){
    			$data = array('comp_id' => $_REQUEST['id']);
				$result = $this->model_companies->selectIDDetail($data);
				if(count($result) >0){	
					$picture = json_decode($result['comp_img_tax'],true);

					if(isset($_FILES['Filedata']['tmp_name']) && $_FILES['Filedata']['tmp_name'] != ""){
						$content = base64_encode(file_get_contents($_FILES['Filedata']['tmp_name']));

						$url = 'http://localhost/alta_upload/api.php';
						$post = 'key='.urlencode('ALTA@UPLOAD@2013').'&upload='.urlencode($content).'&format=json';
						$ch = curl_init();
						curl_setopt($ch, CURLOPT_POST ,1);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
						curl_setopt($ch, CURLOPT_URL, $url);
						curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3");
						curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
						$result = curl_exec($ch);
						curl_close($ch);

						$img_array = json_decode($result,true);

						if($img_array['status_code'] == 200){
							$img_str =  str_replace("localhost/alta_upload","img.altamedia.vn",$img_array['data']['image_url']);

							$picture[] =$img_str;

							$dataArray['comp_img_tax'] = json_encode($picture);

							$this->model_companies->update($dataArray,$_REQUEST['id']);

							echo json_encode(array('result' => 1,'link' => $img_str,'msg' => 'Upload thành công'));
						}
						else echo json_encode(array('result' => 0,'msg' => 'Upload không thành công'));
					}
					else echo json_encode(array('result' => 0,'msg' => 'Upload không thành công'));
				}
			else echo json_encode(array('result' => 0,'msg' => 'Upload không thành công'));
    	}
    	else echo json_encode(array('result' => 0,'msg' => 'Thiếu thông tin'));
	}

	function upload_cmnd(){
    	if(isset($_REQUEST['id'])){
    			$data = array('cust_id' => $_REQUEST['id']);
				$result = $this->model_customer->selectIDDetail($data);
				if(count($result) >0){	
					$picture = json_decode($result['cust_cmnd_images'],true);

					if(isset($_FILES['Filedata']['tmp_name']) && $_FILES['Filedata']['tmp_name'] != ""){
						$content = base64_encode(file_get_contents($_FILES['Filedata']['tmp_name']));

						$url = 'http://localhost/alta_upload/api.php';
						$post = 'key='.urlencode('ALTA@UPLOAD@2013').'&upload='.urlencode($content).'&format=json';
						$ch = curl_init();
						curl_setopt($ch, CURLOPT_POST ,1);
						curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
						curl_setopt($ch, CURLOPT_URL, $url);
						curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3");
						curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
						$result = curl_exec($ch);
						curl_close($ch);

						$img_array = json_decode($result,true);

						if($img_array['status_code'] == 200){
							$img_str =  str_replace("localhost/alta_upload","img.altamedia.vn",$img_array['data']['image_url']);

							$picture[] =$img_str;

							$dataArray['cust_cmnd_images'] = json_encode($picture);

							$this->model_customer->update($dataArray,$_REQUEST['id']);

							echo json_encode(array('result' => 1,'link' => $img_str,'msg' => 'Upload thành công'));
						}
						else echo json_encode(array('result' => 0,'msg' => 'Upload không thành công'));
					}
					else echo json_encode(array('result' => 0,'msg' => 'Upload không thành công'));
				}
			else echo json_encode(array('result' => 0,'msg' => 'Upload không thành công'));
    	}
    	else echo json_encode(array('result' => 0,'msg' => 'Thiếu thông tin'));
	}

	function update_wall(){
			$status=0;	
			$content = $this->input->get_post('content');
			$cust_id = $this->input->get_post('cust_id');
			$creator_id = $this->input->get_post('creater_id');
			$order_id = $this->input->get_post('order_id');
			$day 	 = $this->input->get_post('day');
			$time 	 = $this->input->get_post('time');
			$check_conflict = $this->input->get_post('check_conflict');
			$s=explode('/', $day );
			$date = @strtotime($s[1].'/'.$s[0].'/'.$s[2].' '.$time);
			if(trim($content)==""){
				$status= -1;
				$msg="Nội dung rỗng";
			}else if(trim($cust_id)==""){
				$status= -2;
				$msg="Không tồn tại khách hàng";
			}else if(trim($day)==""){
				$status =-3;
				$msg="Ngày không tồn tại";
			}else{
				if(isset($_REQUEST["led"])){
					$result=$this->model_feeds->insert(
					array(
						'feed_content'=>$content ,'feed_cust_id'=>$cust_id ,
						'feed_creator_id'=> $creator_id,'feed_action_time'=>$date,
						'feed_create_time'=> time()
						)
					);
				}else{
				$result=$this->model_feeds->insert(
					array(
						'feed_content'=>$content ,'feed_cust_id'=>$cust_id ,
						'feed_creator_id'=> $creator_id,'feed_action_time'=>strtotime($day),
						'feed_create_time'=> time()
						)
					);
				}
				
				$status = 1;
				if($result>0){
					$msg="Thành công";
				}else{
					$msg="QUERY ERROR";
				}
			}		
/*
			$result=$this->model_customer->selectIdDetail(array('cust_id'=>$cust_id));

			// Kiểm tra conflict
			$row=$result;
			$check_conflict = false;
			$saleResult = $this->model_customer->checkExistsJoin(array('cust_phone'=>$row["cust_phone"],'cust_email'=>$row["cust_email"],'cust_cmnd'=>$row["cust_cmnd"],'cust_tax_code'=>$row["cust_tax_code"]));
			$my_permisstion =  $this->session->userdata('permission_apps');

		//	print_r($my_permisstion);
			//print_r($saleResult);
			foreach($saleResult as $val ){
				$rs = $this->model_user->selectPermitionApp(array("app_id"=>2,"user_id"=>$val["uId"]));
				//print_r($rs);
			
				if(count($rs)>0){
					$permissions = json_decode($rs["permissions"]);

					foreach($permissions->business as $k => $vl){
						foreach($my_permisstion["business"]  as $ke => $value){

							//echo $k."==".$ke."&&".$value."==on&&".$vl."=="."on"."&&".strtoupper($ke)."==LED ".$row["cust_conflict_id"]."\n";
							if($k == $ke&&$value=="on"&&$vl=="on"&&strtoupper($ke)=="LED"){
								
								//if($row["cust_conflict_id"]!=""){									
									$check_conflict = true;
								//}
							}
						}
					}
				}
				
			}

		echo "check".$check_conflict;
*/
			// SELECT CHECK LẠI KHÁCH HÀNG CONFLICT
			$result = $this->model_customer->selectDetail(array("cust_id"=>$cust_id));

			if($result[0]["cust_conflict_id"]==""){
				$rs = $this->model_customer->selectDetailIdConflict(array("cust_id"=>$cust_id));
			
				if(count($rs)>0){
					$cust_id = $rs[0]["cust_id"];
				}				
			}

			if($check_conflict==true){
				$this->model_conflict->insertConflict(array("url"=>"conflict/review?id=".$cust_id,"title"=>"Xung đột khách hàng trên hợp đồng LED ".$order_id."  <a href='".base_url("conflict/review?id=".$cust_id."&type=LED")."'><strong>Xem chi tiết</strong></a>", "cust_id"=>$cust_id,"uId"=>$creator_id,"content"=>$content,"create_date"=>time(),"order_id"=>$order_id,"type"=>"LED"));
			}

		echo json_encode(array("st"=>$status,'msg'=>$msg));
	}

	function list_cust(){
		$array=array();
		if(isset($_REQUEST["id"])&&$_REQUEST["id"]!=""){
			$cust_id=$_REQUEST["id"];
			$result=$this->model_customer->select(array('my_cust_id'=>$cust_id));	
			if(isset($_REQUEST["debug"])){
				echo $this->db->last_query();
			}
				foreach ($result as $key => $value) {
						$array = array('id'=>$value["cust_id"],'name'=>$value["cust_first_name"]." ".$value["cust_last_name"],'comp_name'=>$value["comp_name"],'comp_id'=>$value["comp_id"]);
					
				}//			
		}else if(isset($_REQUEST["s"])&&$_REQUEST["s"]!=""){		
			$result=$this->model_customer->select(array('where'=>$_REQUEST["s"]));			
				foreach ($result as $key => $value) {
					$array[]=array('id'=>$value["cust_id"],'name'=>$value["cust_first_name"]." ".$value["cust_last_name"],'comp_name'=>$value["comp_name"],'comp_id'=>$value["comp_id"]);
				}
			
		}else{
			$result=$this->model_customer->getListCustFull(array());	
				foreach ($result as $key => $value) {
					$array[]=array('id'=>$value["cust_id"],'name'=>$value["cust_first_name"]." ".$value["cust_last_name"],'comp_name'=>$value["comp_name"],'comp_id'=>$value["comp_id"]);
				}			
			
		}
			
		echo  json_encode($array);
	}
	
	function get_sale(){
		$array = array("result"=>false,"msg"=>"Không tìm thấy sale quản lý khách hàng này");
		$cust_id = $this->input->get_post("cust_id");
		$user_token = $this->input->get_post("token");
		$result = $this->model_customer->selectDetail(array("cust_id"=>$cust_id));
		
		$id = 0;			
		if(count($result)>0){
			$id =$result[0]["uId"];
		}else{
			$array = array("result"=>false,"msg"=>"Khách hàng không tồn tại");
		}
		
		$result = file_get_contents("http://localhost/ht/hrm/api/search_user_by_app?token=".$user_token."&app_name=AM_SALE_SUPPORT");
		$array = array("result"=>false,"msg"=>"Không tìm thấy sale quản lý khách hàng này");
		$json = json_decode($result,true);
		if($json["result"]==true){
			foreach($json["users"] as $key =>$val){
				if($val["user_id"]==$id){
					$array = array("result"=>true,"user_fullname"=>$val["user_fullname"],"user_id"=>$val["user_id"]);
				}
			}
		}else{
			$array = array("result"=>false,"msg"=>$json["msg"]);
		}
		
	echo  json_encode($array);
	}
	
	function extend_token(){
		$user_token = $this->input->get_post("token");		
		$result = file_get_contents("http://localhost/ht/hrm/api/extend_token?token=".$user_token."&app_name=AM_SALE_SUPPORT");
		$json = json_decode($result,true);
		$json["url"]="http://login.alta.com.vn/?redirect=http://crm.altamedia.vn&out";
		
		
	
		if($json["result"]==true){
			$expire_date = $json["expire_date"];
			$this->session->set_userdata('expire_date',$expire_date);
		}
		echo json_encode($json);
	}
}